package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.AfterSaleTicket;
import com.sl.au.entity.AfterSaleTicketAdvice;
import com.sl.au.entity.AfterSaleTicketBack;
import com.sl.au.entity.Attachment;
import com.sl.au.entity.Contract;
import com.sl.au.entity.JPushMsg;
import com.sl.au.entity.Module;
import com.sl.au.entity.User;
import com.sl.au.service.AfterSaleOutHouseService;
import com.sl.au.service.AfterSaleTicketService;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.ContractService;
import com.sl.au.service.ExdeviExdePersonRoleInfoService;
import com.sl.au.service.JGPushService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.utils.ExdeUtil;

/*
 * 售后服务单
 */

@RestController
@RequestMapping(value = "/ui/afterSaleTicket")
public class AfterSaleTicketController extends BaseController {
	@Autowired
	AfterSaleTicketService afterSaleTicketService;
	@Autowired
	AfterSaleOutHouseService afterSaleOutHouseService;
	@Autowired
	OptionService optionService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	ContractService contractService;
	@Autowired
	JGPushService jPushService;
	@Autowired
	ExdeviExdePersonRoleInfoService exdeviExdePersonRoleInfoService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("afterSaleTicket/ticketindex");
		Module module = this.getPageModule("aftersaleticket");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String roleName = a.getRole().getName();
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("roleName", roleName);
		modelAndView.addObject("module", module);
		return modelAndView;
	}
	
	@RequestMapping(value = "/afterSaleView",method = RequestMethod.GET)
	public ModelAndView searchindex() {
		ModelAndView modelAndView = this.createLayoutView("afterSaleTicket/afterSaleViewindex");
		Module module = this.getPageModule("afterSaleView");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String roleName = a.getRole().getName();
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("roleName", roleName);
		modelAndView.addObject("module", module);
		return modelAndView;
	}
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String, Object> getServicePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String isSumbit = request.getParameter("isSumbit");
		String afterSaleType = request.getParameter("afterSaleType");
		if (isSumbit == null) {
			isSumbit = "";
		}
		if (afterSaleType == null) {
			afterSaleType = "";
		}
		if (key == null) {
			key = "";
		}
		Module module = this.getPageModule("aftersaleticket");
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String roleName = a.getRole().getName();
		String superior = a.getUser().getSaleArea().getSuperior();
		String areaId = a.getUser().getSaleArea().getId();
		Map<String, String> condition = new HashMap<String, String>();
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("userId", userId);
		condition.put("roleName", roleName);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		condition.put("isSumbit", isSumbit);
		condition.put("afterSaleType", afterSaleType);
		List<AfterSaleTicket> afterSaleTickets = afterSaleTicketService.getAfterSaleTicket(start, length, condition,null, null);
		long count = afterSaleTicketService.getTicketCount(condition);
		List<AfterSaleTicket> newafterSaleTickets=new ArrayList<AfterSaleTicket>();
		for(AfterSaleTicket r : afterSaleTickets){
			String parentId=r.getId();
			List<Attachment> l= attachmentService.getRepository().findByParentId(parentId);
			int num = l.size();
			r.setAttachNumber(num);
			newafterSaleTickets.add(r);
		}
		map.put("data", newafterSaleTickets);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 引入合同弹窗table数据
	@RequestMapping(value = "/getContractPage", method = RequestMethod.GET)
	public Map<String, Object> getContractPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		List<Contract> contracts = afterSaleTicketService.getContract(start, length, key, null, null);
		long count = afterSaleTicketService.getTicketRepository().getContractCount(key);
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 新增售后内勤单
	@RequestMapping(value = "addTicket", method = RequestMethod.GET)
	public ModelAndView serviceAdd(HttpServletRequest request) {
		String ticketType = request.getParameter("ticketType");
		ModelAndView mv = this.createLayoutView("afterSaleTicket/newPayment");
		Account a = this.getMyAccount();
		User user = a.getUser();
		String superior = a.getUser().getSaleArea().getSuperior();
		List<User> allSuperiorMen = contractService.getAllSuperiorMenBySuperior(superior);
		mv.addObject("allSuperiorMen", allSuperiorMen);
		mv.addObject("user", user);
		mv.addObject("ticketType", ticketType);
		mv.addObject("serviceDate", new Date());
		return mv;
	}
	//移动端获取提交人
	@RequestMapping(value = "allSuperiorMen", method = RequestMethod.GET)
	public Map<String, Object> getAllSuperiorMen(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior();
		List<User> allSuperiorMen = contractService.getAllSuperiorMenBySuperior(superior);
		map.put("allSuperiorMen", allSuperiorMen);
		return map;
	}
	// 售后查看详情
	@RequestMapping(value = "/ticketDetail", method = RequestMethod.GET)
	public ModelAndView ticketDetail(HttpServletRequest request) {
		String ticketId = request.getParameter("ticketId");
		String type = request.getParameter("afterSaleType");
		ModelAndView mv = null;
		if (type.equals("三包办理")) {
			mv = this.createLayoutView("afterSaleTicket/threeGuaranteeDetail");
		} else {
			mv = this.createLayoutView("afterSaleTicket/ticketDetail");
		}
		AfterSaleTicket afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);
		// tab2页数据
		List<AfterSaleTicketBack> afterSaleTicketBacks = afterSaleOutHouseService.getRepository()
				.getTicketTab2Data(ticketId);
		// tab3页数据
		List<AfterSaleTicketAdvice> afterSaleTicketAdvices = afterSaleOutHouseService.getRepository()
				.getTicketTab3Data(ticketId);
		AfterSaleTicketBack afterSaleTicketBack = afterSaleTicketBacks.get(0);
		AfterSaleTicketAdvice afterSaleTicketAdvice = afterSaleTicketAdvices.get(0);
		mv.addObject("afterSaleTicketBack", afterSaleTicketBack);
		mv.addObject("afterSaleTicketAdvice", afterSaleTicketAdvice);
		mv.addObject("afterSaleTicket", afterSaleTicket);
		return mv;
	}

	// 服务单编辑
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView editTicket(HttpServletRequest request) {
		ModelAndView mv = this.createLayoutView("afterSaleTicket/ticketEdit");
		String ticketId = request.getParameter("ticketId");
		AfterSaleTicket afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);
		Account a = this.getMyAccount();
		User user = a.getUser();
		String superior = a.getUser().getSaleArea().getSuperior();
		List<User> allSuperiorMen = contractService.getAllSuperiorMenBySuperior(superior);
		mv.addObject("allSuperiorMen", allSuperiorMen);
		mv.addObject("ticket", afterSaleTicket);
		mv.addObject("user", user);
		return mv;
	}

	// 三包审批单
	@RequestMapping(value = "threeGuaranteesApprove", method = RequestMethod.GET)
	public ModelAndView threeGuaranteesApprove(HttpServletRequest request) {
		ModelAndView mv = this.createLayoutView("afterSaleTicket/threeGuaranteesApprove");
		return mv;
	}

	// 保存售后服务单
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveTicket(HttpServletRequest request, @RequestBody AfterSaleTicket afterSaleTicket) {
		Map<String, Object> map = new HashMap<String, Object>();
		AfterSaleTicket ticket = afterSaleTicketService.getTicketRepository().findOne(afterSaleTicket.getId());
		Account a = this.getMyAccount();
		User user = a.getUser();
		if(afterSaleTicket.getUser()==null) afterSaleTicket.setUser(user);
		afterSaleTicketService.getTicketRepository().save(afterSaleTicket);
		String content = "";
		if (ticket != null) {
			content = "编辑" + afterSaleTicket.getAfterSaleType() + "售后服务单【" + afterSaleTicket.getUnitName() + "】";
		} else {
			content = "新增" + afterSaleTicket.getAfterSaleType() + "售后服务单【" + afterSaleTicket.getUnitName() + "】";
		}
		operateLogService.log(user, "售后服务单申请", content);
		String ticketId = afterSaleTicket.getId();
		Date createTime = afterSaleTicket.getCreateTime();

		map.put("code", 0);
		map.put("ticketId", ticketId);
		map.put("createTime", createTime);
		return map;
	}

	// 删除售后服务单
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public Map<String, Object> delTicket(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		Account a = this.getMyAccount();
		User user = a.getUser();
		List<AfterSaleTicket> afterSaleTickets = new ArrayList<AfterSaleTicket>();
		for (int i = 0; i < id.length; i++) {
			String ticketId = id[i];
			AfterSaleTicket afterSaleTicket = new AfterSaleTicket();
			afterSaleTicket.setId(ticketId);
			afterSaleTickets.add(afterSaleTicket);
			afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);
			afterSaleTicketService.getBackRepository().deleteBack(ticketId);
			afterSaleTicketService.getAdviceRepository().deleteAdvice(ticketId);
			List<Attachment> attachs = attachmentService.getRepository().findByParentId(ticketId);
			attachmentService.getRepository().deleteInBatch(attachs);
			String content = "删除售后服务单【" + afterSaleTicket.getUnitName() + "】";
			operateLogService.log(user, "售后服务单申请", content);
		}
		afterSaleTicketService.getTicketRepository().deleteInBatch(afterSaleTickets);
		map.put("code", 0);
		return map;
	}

	// 提交时保存afterSaleTicketAdvice和afterSaleBack数据
	@RequestMapping(value = "/saveAdviceAndBack", method = RequestMethod.POST)
	public Map<String, Object> saveAdviceAndBack(HttpServletRequest request,
			@RequestBody AfterSaleTicketBack afterSaleTicketBack) {
		Map<String, Object> map = new HashMap<String, Object>();
		afterSaleTicketService.getBackRepository().save(afterSaleTicketBack);
		AfterSaleTicketAdvice afterSaleTicketAdvice = new AfterSaleTicketAdvice();
		AfterSaleTicket at = afterSaleTicketBack.getAfterSaleTicket();
		afterSaleTicketAdvice.setAfterSaleTicket(at);
		afterSaleTicketService.getAdviceRepository().save(afterSaleTicketAdvice);
		// 增加操作日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		
		AfterSaleTicket ticket = afterSaleTicketService.getTicketRepository().findOne(at.getId());
		
		//String superior = user.getSaleArea().getSuperior();
		String areaName = user.getSaleArea().getAreaName();
		List<String> list = new ArrayList<>();
		List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("内勤", "售后服务处");
		for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
			list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
		}
		System.out.println("内勤"+exdeviExdePersonRoleInfos.size());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("售后信息待处理：" + user.getName() + "提交合同号为：" + at.getContractCode() + "的售后信息");
		msg.setTitle("售后信息" + at.getAfterSaleType());
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "提交售后服务单【" + ticket.getUnitName() + "】";
		operateLogService.log(user, "售后服务单申请", content);
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}
	// 
	/**提交时保存afterSaleTicketAdvice和afterSaleBack数据  mobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/mobileSaveAdviceAndBack", method = RequestMethod.GET)
	public Map<String, Object> mobileSaveAdviceAndBack(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ticketId=request.getParameter("ticketId");
		AfterSaleTicket ticket = afterSaleTicketService.getTicketRepository().findOne(ticketId);
		AfterSaleTicketAdvice afterSaleTicketAdvice = new AfterSaleTicketAdvice();
		AfterSaleTicketBack afterSaleTicketBack=new AfterSaleTicketBack();
		afterSaleTicketAdvice.setAfterSaleTicket(ticket);
		afterSaleTicketBack.setAfterSaleTicket(ticket);
		afterSaleTicketService.getAdviceRepository().save(afterSaleTicketAdvice);
		afterSaleTicketService.getBackRepository().save(afterSaleTicketBack);
		// 增加操作日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		
		List<String> list = new ArrayList<>();
		List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("内勤", "售后服务处");
		for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
			list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
		}
		System.out.println("内勤"+exdeviExdePersonRoleInfos.size());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("售后信息待处理：" + user.getName() + "提交合同号为：" + ticket.getContractCode() + "的售后信息");
		msg.setTitle("售后信息" + ticket.getAfterSaleType());
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "提交售后服务单【" + ticket.getUnitName() + "】";
		operateLogService.log(user, "售后服务单申请", content);
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}
	
	/**客户信息页面加载客户相关售后信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getAfterSalepage", method = RequestMethod.GET)
	public Map<String, Object> getAfterSalePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if(key==null){
			key="";
		}
		String  customerId= request.getParameter("customerId");
		List<AfterSaleTicket> afterSaleTickets = afterSaleTicketService.geSaleTicketpage(start, length, key, customerId, null, null);
		long count = afterSaleTicketService.getTicketCount(key, customerId);
		map.put("data", afterSaleTickets);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

}
